package ar.com.ford.it.fullEconomics.persistence.dao;

import java.sql.Timestamp;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp02Commodity;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp03Commodpart;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;
import com.ford.it.persistence.PersistenceManager;
import com.ford.it.persistence.Query;
import com.ford.it.persistence.Transaction;

public class CommodityPartDao extends Dao {
    private static final String CLASS_NAME = CommodityPartDao.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);

    /**
     * Devuelve el commodity al cual la parte pertenece en la fecha actual.
     * 
     * @param part
     * @return
     * @throws PersistenceException
     */
    public Teesp02Commodity getPartsEffectiveCommodity(Teesp01Part part)
            throws PersistenceException {

        String METHOD_NAME = "getPartsEffectiveCommodity";
        log.entering(CLASS_NAME, METHOD_NAME);

        Teesp02Commodity result = null;
        Teesp03Commodpart commPart = null;
        Collection<Teesp03Commodpart> commPartCol = null;
        Iterator<Teesp03Commodpart> commPartIt = null;
        Timestamp maxDateIn = null;

        // Busco todos los commoditys relacionados a la pieza
        PersistenceManager pm = PersistenceUtil.getPersistenceManager();
        Query query = pm.newQuery("findCommodParts", Teesp03Commodpart.class);
        query.setParameters(part, "effective");
        commPartCol = (Collection) pm.executeQuery(query);

        // busco por fecha, y devuelvo aquel commodity que tiene la mayor fecha
        // de ingreso
        if (!commPartCol.isEmpty()) {
            commPartIt = commPartCol.iterator();
            commPart = commPartIt.next();
            result = commPart.getTeesp02Commodity();
            maxDateIn = commPart.getEesp03CommodPartInDateY();
            while (commPartIt.hasNext()) {
                commPart = commPartIt.next();
                if (maxDateIn.getTime() < commPart.getEesp03CommodPartInDateY()
                        .getTime()) {
                    maxDateIn = commPart.getEesp03CommodPartInDateY();
                    result = commPart.getTeesp02Commodity();
                }
            }
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

    /**
     * Devuelve el commodity al cual la parte pertenece en la fecha actual.
     * 
     * @param commPart
     * @return
     * @throws PersistenceException
     */
    public Teesp03Commodpart getEffectiveCommPart(Teesp03Commodpart commPart)
            throws PersistenceException {

        String METHOD_NAME = "getEffectiveCommPart";
        log.entering(CLASS_NAME, METHOD_NAME);

        Teesp03Commodpart result = null;

        PersistenceManager pm = PersistenceUtil.getPersistenceManager();
        Query query = pm.newQuery("findEffectiveCommodPart",
                Teesp03Commodpart.class);
        query.setParameters(commPart);
        result = (Teesp03Commodpart) pm.executeQuery(query);
        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

    /**
     * Da de alta el commPart pasado por parametro
     * 
     * @param commPart
     * Debe tener cargado el nombre del Part
     */
    public void createCommPart(Teesp03Commodpart commPart)
            throws PersistenceException {

        String METHOD_NAME = "createCommPart";
        log.entering(CLASS_NAME, METHOD_NAME);

        Transaction tx = null;

        tx = PersistenceUtil.getTransaction();
        tx.registerInsert(commPart);

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Devuelve el commodity part previo al actual
     * 
     * @param commPart
     * @return
     * @throws PersistenceException
     */
    public Teesp03Commodpart getPrevCommPart(Teesp03Commodpart commPart)
            throws PersistenceException {

        String METHOD_NAME = "getPartsEffectiveCommodity";
        log.entering(CLASS_NAME, METHOD_NAME);

        Teesp03Commodpart result = null;
        Teesp03Commodpart tempCommPart = null;
        Collection<Teesp03Commodpart> commPartCol = null;
        Iterator<Teesp03Commodpart> commPartIt = null;
        Timestamp maxDateIn = null;

        // Busco todos los commoditys relacionados a la pieza
        PersistenceManager pm = PersistenceUtil.getPersistenceManager();
        Query query = pm.newQuery("findCommodParts", Teesp03Commodpart.class);
        query.setParameters(commPart.getTeesp01Part(), "effective");
        commPartCol = (Collection) pm.executeQuery(query);

        // busco por fecha, y devuelvo aquel commodity que tiene la mayor fecha
        // de ingreso
        if (!commPartCol.isEmpty()) {
            commPartIt = commPartCol.iterator();
            result = commPartIt.next();
            maxDateIn = result.getEesp03CommodPartInDateY();
            while (commPartIt.hasNext()) {
                tempCommPart = commPartIt.next();
                if (maxDateIn.getTime() < tempCommPart
                        .getEesp03CommodPartInDateY().getTime()) {
                    maxDateIn = tempCommPart.getEesp03CommodPartInDateY();
                    result = tempCommPart;
                }
            }
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

    /**
     * devuelve las partes pertenecientes a commodity en la fecha actual
     * 
     * @param commodity
     * @return
     * @throws PersistenceException
     */
    public Collection<Teesp01Part> findCommodityParts(Teesp02Commodity commodity)
            throws PersistenceException {

        String METHOD_NAME = "findCommodityParts";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teesp01Part> result = new Vector<Teesp01Part>();
        Collection<Teesp03Commodpart> commPartCol = null;

        // Busco todos los registros e commodParts que tienen esa commodity
        PersistenceManager pm = PersistenceUtil.getPersistenceManager();
        Query query = pm.newQuery("findCommoditysParts",
                Teesp03Commodpart.class);
        query.setParameters(commodity);
        commPartCol = (Collection) pm.executeQuery(query);
        // busco todas las partes qeu se encuentran acualmente en ese comodity
        for (Teesp03Commodpart commPart : commPartCol) {
            result.add(commPart.getTeesp01Part());
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

    /**
     * Busca Commodity Parts validas en la fecha "date" para el Commodity
     * "commodity"
     * 
     * @param commodity
     * @param date
     * @return
     * @throws PersistenceException
     */
    public Collection<Teesp03Commodpart> findCommodityPartsByDate(
                                                                  Teesp02Commodity commodity,
                                                                  Timestamp date)
            throws PersistenceException {
        String METHOD_NAME = "findCommodityPartsByDate";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teesp03Commodpart> res = null;

        PersistenceManager pm = PersistenceUtil.getPersistenceManager();
        Query query = pm.newQuery("findCommodityPartsByDate",
                Teesp03Commodpart.class);
        query.setParameters(commodity, date);
        res = (Collection) pm.executeQuery(query);

        log.exiting(CLASS_NAME, METHOD_NAME);
        return res;
    }
}
